﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using WebStore.Domain.Entities;
using WebStore.Domain.Entities.Enum;

namespace WebStore.Web.App.Utility.Attributes
{
    public class RoleAttribute : ActionFilterAttribute
    {
        private readonly IList<RoleType> _permissions;

        [Dependency]
        public Entities Entities { get; set; }


        public RoleAttribute(params RoleType[] permissionses)
        {
            _permissions = permissionses;

        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity == null || !filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" +
                filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
            }

            if (!IsInRole(filterContext.HttpContext.User.Identity.Name))
            {
                filterContext.HttpContext.Response.StatusCode = 302;
                filterContext.Result = new RedirectResult("Permission");
            }
        }

        private bool IsInRole(string username)
        {
            if (string.IsNullOrEmpty(username))
                return false;
            return
                Entities.Users.Any(
                    x => x.Email == username && x.UserRoles.Any(q => _permissions.Contains(q.Role.RoleType)));
        }


    }
}